﻿using System.IO;
using System.IO.Compression;

namespace SiMay.Sockets.UtilityHelper
{
    /// <summary>
    /// 数据压缩和解压缩
    /// </summary>
    class DataCompressHelper
    {
        /// <summary>
        /// 数据压缩
        /// </summary>
        /// <param name="data">数据</param> 
        /// <returns></returns>
        public static byte[] DataCompress(byte[] data)
        {
            using (MemoryStream _memoryStream = new MemoryStream())
            {
                using (DeflateStream _deflateStream = new DeflateStream(_memoryStream, CompressionMode.Compress, true))
                {
                    _deflateStream.Write(data, 0, data.Length);
                    _deflateStream.Close();
                }
                return _memoryStream.ToArray();
            }
        }

        /// <summary>
        /// 数据解压缩
        /// </summary>
        /// <param name="data">被压缩的数据</param>
        /// <returns></returns>
        public static byte[] DataDecompress(byte[] data)
        {
            byte[] buffer = null;
            try
            {
                MemoryStream ms = new MemoryStream(data);
                DeflateStream deflateStream = new DeflateStream(ms, CompressionMode.Decompress, true);
                MemoryStream msreader = new MemoryStream();
                buffer = new byte[0x1000];
                while (true)
                {
                    int reader = deflateStream.Read(buffer, 0, buffer.Length);
                    if (reader <= 0)
                    {
                        break;
                    }
                    msreader.Write(buffer, 0, reader);
                }
                deflateStream.Close();
                ms.Close();
                msreader.Position = 0;
                buffer = msreader.ToArray();
                msreader.Close();
            }
            catch { }
            return buffer;
        }
    }
}
